package productconsume;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/19 17:42
 * @Version 1.0
 */
public class PCLockAccurate {
    public static void main(String[] args) {
        TaskLockAccurate task = new TaskLockAccurate();
        System.out.println("=====开始A执行完执行B，B执行完执行C...=======");
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    task.A();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "a").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    task.B();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "b").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    task.C();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "c").start();


    }


}

class TaskLockAccurate {
    int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    int flag = 1;

    public void A() throws InterruptedException {
        lock.lock();

        try {
            while (flag != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + ":" + "AAAAA");
            flag = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void B() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 2) {
                condition2.await();
            }
            this.num--;
            System.out.println(Thread.currentThread().getName() + ":" + "BBBBB");
            flag = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void C() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + ":" + "CCCC");
            flag = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
